/**
 * 
 */
package com.jxc.action.xsgl;

import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.model.po.BasicArgument;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VAuditRecord;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VMember;
import com.jxc.model.vo.VPointUsedRecord;
import com.jxc.model.vo.VRemindWarn;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VSaleReturnlist;
import com.jxc.model.vo.VSalelist;
import com.jxc.model.vo.VSalelistItem;
import com.jxc.model.vo.VUser;
import com.jxc.service.AuditRecordServiceI;
import com.jxc.service.BasicArgumentServiceI;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.MemberServiceI;
import com.jxc.service.PointUsedRecordServiceI;
import com.jxc.service.RemindWarnServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.SaleReturnlistServiceI;
import com.jxc.service.SalelistItemServiceI;
import com.jxc.service.SalelistServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.Constants;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author Tino
 * 
 */
@Namespace("/xsgl")
@Action(value = "salelistAction", results = { @Result(name = "saletotal", location = "/sale/saleTotal.jsp"),
		                                      @Result(name = "settlementTotal", location = "/sale/settlementTotal.jsp")})
public class SalelistAction extends BaseAction implements ModelDriven<VSalelist> {
	private final static Logger logger = Logger.getLogger(SalelistAction.class);

	private VSalelist model = new VSalelist();
	private String items;
	private String mSerial;

	@Autowired
	private SalelistServiceI salelistService;
	@Autowired
	private SalelistItemServiceI salelistItemService;
	@Autowired
	private PointUsedRecordServiceI pointUserRecordService;
	@Autowired
	private GoodsServiceI goodsService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;
	@Autowired
	private MemberServiceI memberService;
	@Autowired
	private AuditRecordServiceI auditRecordService;
	@Autowired
	private SaleReturnlistServiceI saleReturnlistService;
	@Autowired
	private BasicArgumentServiceI basicArumentService;
	@Autowired
	private RemindWarnServiceI remindWarnService;

	public void noAuth_datagrid() throws Exception {
		if (StringUtils.isNotBlank(mSerial)) {
			VMember vm = new VMember();
			vm.setSerial(mSerial);
			List<VMember> vms = memberService.combobox(vm);
			if (vms.size() > 0) {
				model.setMid(vms.get(0).getId());
			} else {
				model.setMid(0l);
			}
		}
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}
		if (model.getRid() != null) {
			this.writeJson(salelistService.datagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(salelistService.datagrid(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					model.setRid(vrepertories.get(0).getId());
					this.writeJson(salelistService.datagrid(model));
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VGoods>());
					this.writeJson(dg);
				}
			}
		}
	}

	public void noAuth_add() {
		logger.info("销售了一批商品!");
		Json j = new Json();
		try {
			model.setRemark(new URLDecoder().decode(model.getRemark(), "UTF-8"));
			/*
			 * ------------------------------------------------------------------
			 * ------------------------------ 保存销售单
			 * ------------------------------
			 * ------------------------------------
			 * ------------------------------
			 */
			Long slId = salelistService.save(model);

			Map<Long, VSalelistItem> itemMap = new HashMap<Long, VSalelistItem>();
			List<VSalelistItem> vslis = new ArrayList<VSalelistItem>();
			Map<Long, VGoods> vgMap = new HashMap<Long, VGoods>();
			List<VGoods> vgoods = new ArrayList<VGoods>();

			String[] itemArr = items.split(",");
			for (int i = 0; i < itemArr.length; i++) {
				Long gid = Long.parseLong(itemArr[i]);
				Double showPrice = Double.parseDouble(itemArr[++i]);
				Integer num = Integer.parseInt(itemArr[++i]);
				Double total = Double.parseDouble(itemArr[++i]);

				VSalelistItem vsli = itemMap.get(gid);
				if (vsli != null) {
					vsli.setNumber(vsli.getNumber() + num);
					vsli.setTotal(vsli.getTotal() + total);
					VGoods vg = vgMap.get(gid);
					vg.setAmount(vg.getAmount() - num);
				} else {
					vsli = new VSalelistItem();
					vsli.setGid(gid);
					vsli.setSalePrice(showPrice);
					vsli.setNumber(num);
					vsli.setTotal(total);
					vslis.add(vsli);
					itemMap.put(gid, vsli);

					VGoods param = new VGoods();
					param.setId(gid);
					List<VGoods> vgoodz = goodsService.combobox(param);
					VGoods vg = vgoodz.get(0);
					vg.setAmount(vg.getAmount() - num);
					vg.setSaleTotal(vg.getSaleTotal() + num);
					vgMap.put(gid, vg);
					vgoods.add(vg);
				}
			}

			/*
			 * ------------------------------------------------------------------
			 * ------------------------------ 保存销售单明细
			 * ----------------------------
			 * --------------------------------------
			 * ------------------------------
			 */
			this.salelistItemService.batchSave(vslis, slId);

			/*
			 * ------------------------------------------------------------------
			 * ------------------------------ 更新商品库存
			 * ----------------------------
			 * --------------------------------------
			 * ------------------------------
			 */
			for (VGoods vg : vgoods) {
				this.goodsService.update(vg);
			}

			/*
			 * ------------------------------------------------------------------
			 * 客户使用了积分来支付，扣除会员使用积分，增加消费金额和消费积分，记录积分使用记录
			 * --------------------------
			 */
			if (model.getMid() != null) {
				VMember param = new VMember();
				param.setId(model.getMid());
				List<VMember> vms = memberService.combobox(param);
				VMember vm = vms.get(0);
				vm.setPoint(vm.getPoint() - model.getPoint());
				Double consume = (model.getRealPay() * 100 - model.getCharge() * 100) / 100;
				vm.setConsume(vm.getConsume() + consume);
				vm.setPoint(vm.getPoint() + (int) Math.floor(consume));
				memberService.update(vm);

				if (model.getPoint() > 0) {
					VPointUsedRecord vpur = new VPointUsedRecord();
					vpur.setDate(model.getDate());
					vpur.setNum(model.getPoint());
					vpur.setMid(model.getMid());
					vpur.setSlid(slId);
					this.pointUserRecordService.save(vpur);
				}

				/*
				 * --------------------------------------------------------------------------------------
				 * 会员积分提醒
				 * --------------------------------------------------------------------------------------
				 */
				BasicArgument ba = this.basicArumentService.getBasricArgumentByKey(model.getRid(), Constants.MIN_POINT_REMIND);
				if (vm.getPoint() > Integer.parseInt(ba.getArgValue())) {
					VRemindWarn vrw = new VRemindWarn();
					vrw.setTime(new Date());
					vrw.setContent("会员[姓名：" + vm.getName() + "，编号：" + vm.getSerial() + "]积分已经达到" + vm.getPoint() + "，请提醒他/她来消费！");
					vrw.setIsDone(false);
					vrw.setUid(vm.getUid());
					this.remindWarnService.save(vrw);
				}
			}

			j.setMsg("添加成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败！");
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
		super.writeJson(j);
	}

	public void noAuth_settlement() {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		VUser vuser = userService.get(sessionInfo.getUserId());

		Json j = new Json();
		VAuditRecord ar = new VAuditRecord();
		try {
			ar.setBeginAudit(model.getBeginDate());
			ar.setEndAudit(model.getEndDate());
			ar.setRid(model.getRid());
			ar.setUid(vuser.getId());

			Double total = 0.0;

			if (model.getBeginDate() != null) {
				String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
				model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
			}

			VAuditRecord param = new VAuditRecord();
			param.setRid(model.getRid());
			param.setOrder("desc");
			param.setSort("endAudit");
			List<VAuditRecord> vars = auditRecordService.combobox(param);
			if (vars.size() > 0) {
				VAuditRecord var = vars.get(0);
				this.getRequest().setAttribute("EndAudit", new SimpleDateFormat("yyyy年MM月dd日").format(var.getEndAudit()));
				Calendar cal = Calendar.getInstance();
				cal.setTime(var.getEndAudit());
				cal.add(Calendar.DAY_OF_MONTH, 1);
				Date systemBeginDate = cal.getTime();

				if (model.getBeginDate() == null) {
					j.setMsg("结算开始时间不能为空！");
					super.writeJson(j);
					return;
				}

				if (systemBeginDate.after(model.getBeginDate())) {
					j.setMsg("结算开始时间早于或等于上次结算时间！");
					super.writeJson(j);
					return;
				}
			}

			if (model.getEndDate() != null) {
				String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
				model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
			}

			if (model.getEndDate().before(model.getBeginDate())) {
				j.setMsg("结算结束时间早于结算开始时间！");
				super.writeJson(j);
				return;
			}

			VSalelist para = new VSalelist();
			para.setRid(model.getRid());
			para.setBeginDate(model.getBeginDate());
			para.setEndDate(model.getEndDate());
			List<VSalelist> vsls = salelistService.combobox(para);
			if (vsls.size() > 0) {
				for (VSalelist vsl : vsls) {
					if (vsl.getPointNum() == null) {
						total += vsl.getTotal();
					} else {
						BasicArgument ba = this.basicArumentService.getBasricArgumentByKey(model.getRid(), Constants.INTEGRAL_CONVERSION_RATIO);
						Double point = (vsl.getPointNum() / Double.parseDouble(ba.getArgValue()));
						if (point < vsl.getTotal()) {
							total += (vsl.getTotal() - point);
						}
					}
				}

				VSaleReturnlist par = new VSaleReturnlist();
				par.setRid(model.getRid());
				par.setBeginDate(model.getBeginDate());
				para.setEndDate(model.getEndDate());
				List<VSaleReturnlist> vsrls = saleReturnlistService.combobox(par);
				if (vsrls.size() > 0) {
					for (VSaleReturnlist vsrl : vsrls) {
						total -= vsrl.getRealReturn();
					}
				}

				DecimalFormat format = new DecimalFormat("0.00");
				total = Double.parseDouble(format.format(total));
			}

			ar.setTotal(total);
			auditRecordService.save(ar);
		} catch (Exception e) {
			logger.info(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("统计异常！");
		}
		super.writeJson(j);
	}

	@Override
	public VSalelist getModel() {
		return model;
	}

	public void noAuth_checkSalelist() {
		DataGrid dataGrid = salelistService.datagridNoPage(model);

		Json json = new Json();
		if (dataGrid.getRows() != null && dataGrid.getRows().size() > 0) {
			writeJson(dataGrid.getRows());
		} else {
			json.setSuccess(false);
			json.setMsg("没有该销售单!");
			writeJson(json);
		}
	}

	public void noAuth_checkItems() {
		writeJson(salelistService.getItems(model));

	}

	public String getItems() {
		return items;
	}

	public void setItems(String items) {
		this.items = items;
	}

	public String getMSerial() {
		return mSerial;
	}

	public void setMSerial(String serial) {
		mSerial = serial;
	}

	/*
	 * --------------------------------------------------------------------------------------
	 * 营业员销售统计
	 * --------------------------------------------------------------------------------------
	 */
	
	public String saleTotal() {
		getSubAuths("SJTJ_YYYXSTJ");
		return "saletotal";
	}
		
	public void datagridTotal() throws Exception {
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}else{
			String beginDateStr = new SimpleDateFormat("yyyy-MM-01").format(new Date());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}else{
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}
		if (model.getRid() != null) {
			this.writeJson(salelistService.datagridTotal(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());		
			
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(salelistService.datagridTotal(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VSalelist> rows = new ArrayList<VSalelist>();
					Long total = 0l;
					for (VRepertory vre : vrepertories) {
						model.setRid(vre.getId());
						DataGrid subDg = salelistService.datagridTotal(model);
						rows.addAll(subDg.getRows());
						//total += subDg.getTotal();					
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					//totalDg.setTotal(total);
					totalDg.setTotal(new Long(rows.size()));
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VSalelist>());
					this.writeJson(dg);
				}
			}
			
		}
	}
	
	/*
	 * --------------------------------------------------------------------------------------
	 * 对账明细统计
	 * --------------------------------------------------------------------------------------
	 */
	
	public String settlementTotal() {
		getSubAuths("SJTJ_DZMX");
		return "settlementTotal";
	}
		
	public void datagridsettlementTotal() throws Exception {
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}else{
			String beginDateStr = new SimpleDateFormat("yyyy-MM-01").format(new Date());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}else{
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}
		if (model.getRid() != null) {
			this.writeJson(salelistService.datagridsettlementTotal(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());		
			
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(salelistService.datagridsettlementTotal(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VSalelist> rows = new ArrayList<VSalelist>();
					Long total = 0l;
					for (VRepertory vre : vrepertories) {
						model.setRid(vre.getId());
						DataGrid subDg = salelistService.datagridsettlementTotal(model);
						rows.addAll(subDg.getRows());
						//total += subDg.getTotal();
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					//totalDg.setTotal(total);
					totalDg.setTotal(new Long(rows.size()));
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VSalelist>());
					this.writeJson(dg);
				}
			}
			
		}
	}
	
	
}
